<template>
  <el-dialog
    minHeight="400px"
    width="990px"
    title="物料目录选择"
    :visible.sync="dialogFormVisible"
    :before-close="inventoryCancel"
    custom-class="sorting-code-number"
    v-if="dialogFormVisible"
  >
    <div class="el-dialog__body-bodys">
      <div class="container">
        <div class="header">已选择({{ inventoryTableData2.length }}个)</div>
        <div class="ccui-multifunctional-table-wrapper">
          <el-table
            :data="inventoryTableData2"
            ref="multipleTable2"
            max-height="200px"
            height="99%"
            border
            :fit="true"
            row-key="matNum"
          >
            <el-table-column label="序号" width="45" fixed>
              <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>

            <el-table-column
              v-for="(table, index) in tableTheadOptions"
              :key="index"
              :fixed="table.fixed || false"
              :label="table.label"
              :min-width="table.width"
              :prop="table.prop"
              show-overflow-tooltip
            >
            </el-table-column>

            <el-table-column label="操作" width="50px">
              <template slot-scope="{ row, $index }">
                <el-button
                  size="mini"
                  type="text"
                  @click="inventoryDeleteTable(row, $index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div class="container">
        <!-- 搜索条件开始 -->
        <el-search
          :formProp="inventoryForm"
          @search="inventorySearch"
          @change="inventoryChange"
          width="400px"
          placement="bottom-start"
          class="ccui-highsearch no-print"
        >
          <template slot="search">
            <el-input
              v-model="formData.matName"
              clearable
              searchLabel="设备物资名称"
              placeholder="请输入物资名称模糊查询"
            ></el-input>
            <el-input
              v-model="formData.matNum"
              clearable
              searchLabel="设备物资编号"
              placeholder="请输入物编号称模糊查询"
            ></el-input>
          </template>
        </el-search>
        <!-- 搜索条件结束 -->
        <div class="ccui-multifunctional-table-wrapper">
          <div class="treeTable">
            <el-tree
              v-if="dialogFormVisible"
              ref="tree"
              node-key="onlyId"
              expand-on-click-node
              lazy
              show-line
              :props="treeProps"
              :load="loadNode"
              :default-checked-keys="defaultCheckedKeys"
              :draggable="false"
              @node-click="handleCheckClick"
            >
            </el-tree>
          </div>

          <el-table
            :data="inventoryTableDatas"
            min-height="100px"
            height="90%"
            @selection-change="handleSelectionChange"
            @row-click="rowClick"
            ref="inventoryMultipleTable"
            style="margin: 0 0 0 20px; width: 700px; float: right"
            border
            :fit="true"
            row-key="onlyId"
          >
            <el-table-column width="35" type="selection" reserve-selection />

            <el-table-column label="序号" width="45" align="center" fixed>
              <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>

            <el-table-column
              v-for="(table, index) in tableTheadOptions"
              :key="index"
              :fixed="table.fixed || false"
              :label="table.label"
              :min-width="table.width"
              :prop="table.prop"
              show-overflow-tooltip
            >
            </el-table-column>
          </el-table>
        </div>
        <div
          v-show="inventoryTableDatas.length"
          class="table-footer"
          style="height: 30px"
        >
          <div class="ccui-table-footer">
            <div id="ccui-paging">
              <el-pagination
                :total="inventoryTotal"
                :page-size="inventoryPageSize"
                :current-page="inventoryPageNoCode"
                prev-text="< 上一页"
                next-text="下一页 >"
                background
                layout=" prev, pager, next, jumper"
                popper-class="ccui-paging-page-size-popper"
                @current-change="inventoryHandleCurrentChange"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button size="mini" type="default-mini" @click="inventoryCancel"
        >取 消</el-button
      >
      <el-button size="mini" type="primary-font-mini" @click="inventoryConfirm"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>
<script>
import flexColumnWidth from "@/basa/mixins/flexColumnWidth";
import { generateUUID } from "@/basa/utils";
export default {
  name: "chooseMaterialsCatalogue",
  mixins: [flexColumnWidth],
  props: {
    functionObject: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      treeProps: {
        label: "categoryName",
        children: "childNodes",
        isLeaf: "leaf"
      },
      // 搜索条件
      searchInputArr: [
        { label: "物资名称", value: "matName" },
        { label: "物资编码", value: "matNum" }
      ],
      formData: {
        matName: "",
        matNum: "",
        pageNo: 1,
        pageSize: 10,
        catalogId: ""
      },
      formDataSearch: {},
      dialogFormVisible: false,
      inventoryForm: {},
      inventoryTableDatas: [],
      inventoryTotal: 0,
      inventoryPageNoCode: 1,
      inventoryPageSize: 10,
      inventoryTableData2: [], //所有选中的数据包含跨分页数据
      tableTheadOptions: [
        {
          prop: "matNum",
          label: "设备物资编号",
          width: 110
        },
        {
          prop: "matName",
          label: "设备物资名称",
          width: 250
        },
        { prop: "parentCategoriesCode", label: "分类编码" },
        { prop: "parentCategoriesName", label: "分类名称" },
        { prop: "unitStr", label: "计量单位", width: 80 }
      ],
      selectTreeNode: {
        categoryName: "常用编码",
        childNodes: [],
        leaf: true,
        onlyId: 0
      },
      defaultCheckedKeys: [0]
    };
  },
  methods: {
    handleCheckClick(item) {
      this.$refs.tree.setCheckedKeys([]);
      this.defaultCheckedKeys = [];
      this.selectTreeNode = item;
      if (item.leaf) {
        this.formDataSearch.matName = "";
        this.formDataSearch.matNum = "";
        this.formData.matName = "";
        this.formData.matNum = "";
        this.formData.pageNo = 1;
        this.formData.catalogId = item.categoryCode;
        this.formDataSearch.pageNo = 1;
        this.formDataSearch.catalogId = item.categoryCode;
        this.getList(item);
      }
    },
    loadNode(node, resolve) {
      let data = {};
      // if (node.level == 0) {
      //   resolve([
      //     {
      //       leaf: false,
      //       categoryName: "类别",
      //       categoryCode: "1-1",
      //       childNodes: []
      //     }
      //   ]);
      // }
      if (node.level == 0) {
        resolve([
          {
            leaf: true,
            onlyId: 0,
            categoryName: "常用编码",
            childNodes: []
          },
          {
            leaf: false,
            onlyId: 1,
            categoryName: "设备物资类别",
            childNodes: []
          },
          {
            leaf: false,
            onlyId: 2,
            categoryName: "常用类别",
            childNodes: []
          }
        ]);
      }
      if (node.level == 1) {
        if (node.data.categoryName == "设备物资类别") {
          data = {
            categoryCode: "0"
          };
          this.functionObject.materialTree(data).then(res => {
            if (res.data.code == 0) {
              if (node.level <= 1) {
                res.data.data.categoryList.forEach(item => {
                  if (item.isLeaf == 1) {
                    item.leaf = true;
                  }
                  item.onlyId = generateUUID();
                });
                resolve(res.data.data.categoryList);
              } else {
                res.data.data.categoryList.forEach(item => {
                  if (item.isLeaf == 1) {
                    item.leaf = true;
                  }
                  item.treeCheckbox = true;
                  item.onlyId = generateUUID();
                });
                resolve(res.data.data.categoryList);
              }
            } else {
              resolve && resolve([]);
            }
          });
        }
        if (node.data.categoryName == "常用类别") {
          this.functionObject.commonCategories({}).then(res => {
            if (res.data.code == 0) {
              resolve(
                res.data.data.rows.map(n => ({
                  ...n,
                  leaf: true,
                  onlyId: generateUUID()
                }))
              );
            } else {
              resolve && resolve([]);
            }
          });
        }
      }
      if (node.level > 1) {
        data = {
          categoryCode: node.data.categoryCode
        };
        this.functionObject.materialTree(data).then(res => {
          if (res.data.code == 0) {
            if (node.level <= 1) {
              res.data.data.categoryList.forEach(item => {
                if (item.isLeaf == 1) {
                  item.leaf = true;
                }
                item.onlyId = generateUUID();
              });
              resolve(res.data.data.categoryList);
            } else {
              res.data.data.categoryList.forEach(item => {
                if (item.isLeaf == 1) {
                  item.leaf = true;
                }
                item.treeCheckbox = true;
                item.onlyId = generateUUID();
              });
              resolve(res.data.data.categoryList);
            }
          } else {
            resolve && resolve([]);
          }
        });
      }
    },
    getMaterialList(reqObj) {
      let obj = {};
      obj = typeof reqObj == "object" ? reqObj : obj;
      this.functionObject.materialList(obj).then(res => {
        if (res.data.code == 0) {
          this.inventoryTableDatas = res.data.data.rows.map(n => ({
            ...n,
            onlyId: generateUUID()
          }));
          this.inventoryTotal = res.data.data.recordsTotal;
          this.inventoryPageNoCode = res.data.data.pageNo;
          this.$nextTick(() => {
            this.$refs.inventoryMultipleTable.doLayout();
          });
        }
      });
    },
    getCommonCodes(val = {}) {
      this.functionObject.commonCodes(val).then(res => {
        this.inventoryTableDatas = res.data.data.rows.map(n => ({
          ...n,
          parentCategoriesCode: n.thirdCategoriesOfCode,
          parentCategoriesName: n.thirdCategoriesOfName,
          onlyId: generateUUID()
        }));
        this.inventoryTotal = res.data.data.recordsTotal;
      });
    },
    getCommonCategories(val = {}) {
      this.functionObject.commonCategories(val).then(res => {
        if (res.data.data.rows.length) {
          this.inventoryTableDatas = res.data.data.rows.map(n => ({
            matNum: n.thirdCategoriesOfCode,
            matName: n.thirdCategoriesOfName,
            parentCategoriesCode: n.categoryCode,
            parentCategoriesName: n.categoryName,
            onlyId: generateUUID()
          }));
        } else {
          this.inventoryTableDatas = [];
        }
        this.inventoryTotal = res.data.data.recordsTotal;
      });
    },
    inventoryHandleCurrentChange(val) {
      this.formData.pageNo = val;
      this.formDataSearch.pageNo = val;

      this.getList(this.selectTreeNode);
    },
    inventorySearch(searchData) {
      this.formData.pageNo = 1;
      this.formDataSearch = {
        ...searchData,
        pageNo: 1,
        catalogId: this.formData.catalogId
      };
      this.getList(this.selectTreeNode);
    },
    getList({ leaf, categoryName }) {
      if (!leaf) return;
      if (categoryName == "常用编码") {
        this.getCommonCodes(this.formDataSearch);
      } else if (categoryName == "常用类别") {
        this.getCommonCategories(this.formDataSearch);
      } else {
        this.getMaterialList(this.formDataSearch);
      }
    },
    inventoryChange(index, key, value) {
      this.formData.matName = "";
      this.formData.matNum = "";
    },
    // 删除
    inventoryDeleteTable(row, index) {
      this.inventoryTableData2 = this.inventoryTableData2.filter(
        item => item.pkPurmatdetl !== row.pkPurmatdetl
      );
      this.$refs.inventoryMultipleTable.toggleRowSelection(row, false);
    },
    inventoryConfirm() {
      if (!this.inventoryTableData2.length) {
        return this.$showErrorMessage("未选择数据，请重试");
      }
      this.dialogFormVisible = false;
      this.$emit("confirm", this.inventoryTableData2);
      this.resetParams();
    },
    inventoryCancel() {
      this.dialogFormVisible = false;
      this.resetParams();
    },
    // 重置表单
    inventoryReset() {
      this.$refs.inventoryForm.resetFields();
    },
    // 单选行数据
    // 每行的唯一值
    // 选择行数据
    handleSelectionChange(selection) {
      // 数据去重 并 赋值
      this.inventoryTableData2 = selection;
      this.$nextTick(() => {
        this.$refs.multipleTable2.doLayout();
      });
    },

    // 点击行单选
    rowClick(row, event, column) {
      // const isExist = this.inventoryTableData2
      //   .map(n => n.matNum)
      //   .includes(row.matNum);
      // this.handleSelectionChange([row]);
      // console.log(">>>>>>>>", isExist, "<<<<<<<<");
      // this.$refs.inventoryMultipleTable.toggleRowSelection(row, isExist);
    },

    resetParams() {
      this.dialogFormVisible = false;
      this.formData.pageNo = 1;
      this.formDataSearch.pageNo = 1;
      this.inventoryPageSize = 10;
      this.inventoryForm = {};
      this.inventoryTableDatas = [];
      this.inventoryTableData2 = [];
      this.defaultCheckedKeys = [0];
    }
  },
  watch: {
    dialogFormVisible(n) {
      if (n) this.getCommonCodes(); // 默认查第一条
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/ .ccui-multifunctional-table-wrapper {
  height: 87%;
  .el-table tbody tr:last-child td {
    border-bottom: 1px solid #edf2fc !important;
  }
}
/deep/ .container:nth-child(1) {
  height: 40% !important;
}
/deep/ .container:nth-child(2) {
  height: 60% !important;
}
/deep/ .el-tree-node.is-current > .el-tree-node__content span,
/deep/ .el-tree-node.is-checked > .el-tree-node__content span {
  color: #0089ef !important;
}
/deep/ .el-search .ccui-search-wrapper {
  margin: 0 0 10px 0;
}
/deep/ .sorting-code-number .el-dialog__body {
  min-height: 380px;
}
.treeTable {
  width: 200px;
  height: 110%;
  overflow: auto;
  border: 1px solid #f1f1f1;
  float: left;
}
.inventory {
  display: inline-block;
  & + .inventory {
    margin-left: 10px;
  }
  /deep/ .el-dialog__header {
    // display: flex;
    // align-items: center;
    padding: 4px 20px !important;
  }
  /deep/ .el-dialog__title {
    display: inline-block;
    height: 20px;
    line-height: 20px !important;
  }
  /deep/ .revenue-code-number {
    .el-dialog__body {
      width: auto;
      height: auto;
      .ccui-form {
        margin-top: 5px;
      }
    }
  }
  /deep/ .revenue-code-number .el-dialog__body .el-dialog__body-bodys {
    .bodys-right {
      padding: 0;
    }
  }
  /deep/.el-search .el-searchs {
    float: none !important;
  }
  /deep/.el-searchs-box {
    // width: auto !important;
    margin: 0 auto;
  }
  .container {
    border: 1px solid #f1f1f1;
    padding: 10px 20px;
    .header {
      margin-bottom: 10px;
    }
    .table-footer {
      padding: 10px 0;
    }
    .ccui-statistics-card {
      padding: 0;
    }
  }
  /deep/.el-button--text {
    font-size: 13px;
  }
  /deep/.el-input {
    width: 192px;
  }
  .search-btn {
    text-align: center;
    padding: 0 0 20px 0;
  }
  // 搜索条件 启动
  /deep/ .el-form.el-searchs-bottom-form {
    .el-row {
      width: 100%;
    }
    .el-date-editor {
      width: 192px;
      .el-range-input {
        width: 50%;
      }
      .el-range-separator {
        padding: 0 10px 0 5px;
        font-size: 13px;
      }
      .el-range__close-icon,
      .el-range__icon {
        display: none;
      }
    }
  }
  /deep/ .el-dialog__body .el-form .el-form-item:last-child {
    margin-bottom: 16px;
  }
  // 搜索条件 结束
  /deep/ .ccui-multifunctional-table-wrapper .el-table {
    td,
    th.is-leaf {
      border-right: 1px solid #edf2fc;
    }
    // 固定行的高
    .el-table__fixed {
      height: 100% !important;
    }
    td.is-hidden > *,
    th.is-hidden > * {
      visibility: inherit;
    }
  }
}
</style>
